package cn.mengfly.fxtest.app.dialog;

import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;

/**
 * @author Mengfly
 */
public class ConnectionDialog extends Dialog<ConnectionInfo> {

    private final TextField tfHost = new TextField();
    private final TextField tfUser = new TextField();
    private final TextField tfPassword = new TextField();

    public ConnectionDialog(ConnectionInfo initialData) {
        Label hostLabel = new Label("Host");
        Label userLabel = new Label("User");
        Label passwordLabel = new Label("Password");

        VBox vBox = new VBox(
                hostLabel, tfHost,
                userLabel, tfUser,
                passwordLabel, tfPassword
        );

        vBox.setSpacing(10);
        vBox.setPadding(new Insets(40));

        DialogPane dp = getDialogPane();
        setTitle("Connection Info");
        setResultConverter(this::formResult);

        ButtonType bt = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
        dp.getButtonTypes().addAll(bt, ButtonType.CANCEL);
        dp.setContent(vBox);

        init(initialData);
    }

    private void init(ConnectionInfo initialData) {
        if (initialData != null) {
            tfHost.setText(initialData.getHost());
            tfUser.setText(initialData.getUsername());
            tfPassword.setText(initialData.getPassword());
        }
    }

    private ConnectionInfo formResult(ButtonType bt) {
        ConnectionInfo retval = null;
        if (bt.getButtonData() == ButtonBar.ButtonData.OK_DONE) {
            retval = new ConnectionInfo(tfHost.getText(), tfUser.getText(), tfPassword.getText());
        }
        return retval;
    }
}
